package com.synesthesiaconsulting.utils;

import java.util.Random;
import java.security.MessageDigest;

/**
 * Created by IntelliJ IDEA.
 * User: ageer
 * Date: Jul 22, 2008
 * Time: 7:03:59 AM
 * To change this template use File | Settings | File Templates.
 */
public class PasswordUtilities {
    private static String HASHFUNCTION = "SHA-256";
    private static Integer SALTLENGTH = 16;
    private static Integer HASHITERATION = 2000;

    public static byte[] getSalt() {
        byte[] salt = new byte[SALTLENGTH.intValue()];
        Random rgen = new Random();
        rgen.nextBytes(salt);
        return salt;
    }
//    public static String digestPassword(String password) {
//        String ret =  JDBCRealm.Digest(password,HASHFUNCTION,"UTF-8");
//        System.out.println(ret + " " + ret.length());
//        return ret;
//    }
    public static byte[] applySalt(String password, byte[] salt) {
        try {
            byte[] output = password.getBytes("UTF-8");
            MessageDigest digest = MessageDigest.getInstance(HASHFUNCTION);
            for (int i = 0; i < HASHITERATION; i++) {
                digest.reset();
                digest.update(salt);
                output = digest.digest(output);
            }
            return output;
        } catch (Exception e) {
            return null;
        }
    }

}

